﻿Imports Monitoring
Imports System.Collections.ObjectModel
Imports System.Runtime.InteropServices

<StructLayout(LayoutKind.Sequential, Size:=64)>
Public Structure FarOutStruct
    Public A As Integer
    Public B As Short
    Public C As Guid
End Structure


Public Class Form1

    Private WithEvents Mon As FSMonitor
    Private fnInfo As New ObservableCollection(Of FileNotifyInfo)

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Mon.StopWatching()
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim mm As New MemPtr
        Dim b() As Byte

        Mon = New FSMonitor("E:\", Me.Handle)

        lvFiles.View = View.Details

        lvFiles.Columns.Add("File").Width = 340
        lvFiles.Columns.Add("Type").Width = 120

    End Sub

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        End
    End Sub

    Private Sub ToggleMonitorToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ToggleMonitorToolStripMenuItem.Click

        If Mon.IsWatching Then
            Mon.StopWatching()
            tssl2.Text = "Monitor Closed."
            tssl.Text = "0 Total Items."
            lvFiles.VirtualListSize = 0
            fnInfo.Clear()
        Else
            Mon.Watch()
            tssl2.Text = "Monitor Opened."
        End If

    End Sub

    Private Sub Mon_WatchNotifyChange(sender As Object, e As FSMonitorEventArgs) Handles Mon.WatchNotifyChange

        Dim fni As FileNotifyInfo = e.Info

        Do Until fni Is Nothing

            If System.IO.Path.GetFileName(fni.Filename) = "Thumbs.db" Then
                fni = fni.NextEntry
                Continue Do
            End If

            If (e.Info.Actions = FileActions.Added) Then
                fnInfo.Add(e.Info)
            End If
            fni = fni.NextEntry
        Loop

        BeginInvoke(Sub()
                        tssl.Text = fnInfo.Count & " Total Items."
                        lvFiles.VirtualListSize = fnInfo.Count
                    End Sub)

    End Sub

    Private Sub lvFiles_RetrieveVirtualItem(sender As Object, e As RetrieveVirtualItemEventArgs) Handles lvFiles.RetrieveVirtualItem

        Dim fni As FileNotifyInfo = fnInfo(e.ItemIndex)

        Dim li As New ListViewItem

        li.Text = fni.Filename
        li.SubItems.Add(fni.Actions.ToString)
        li.Tag = fni

        e.Item = li
    End Sub

End Class
